package org.amse.tanks.controller;

import org.amse.tanks.model.Model;
import org.amse.tanks.model.ModelConstants;
import org.amse.tanks.model.ModelIO;
import org.amse.tanks.objects.Direction;
import org.amse.tanks.objects.Tank;
import org.amse.tanks.player.Bot;
import org.amse.tanks.player.HumanPlayer;
import org.amse.tanks.player.Player;
import org.amse.tanks.view.UIView;
import org.amse.tanks.view.UIViewConstants;
import org.amse.tanks.view.View;

import java.util.ArrayList;
import java.util.Iterator;

public class LocalController implements ModelConstants, UIViewConstants {
    public LocalController(String[] args) {
        if (args[0].charAt(0) != 'l') {
            System.out.println("Wrong parameters");
            System.exit(-1);
        }

        int botsNumber = BOTS_DEFAULT_NUMBER;
        int humansNumber = HUMANS_DEFAULT_NUMBER;
        if (args.length == 3) {
            botsNumber = Integer.parseInt(args[1]);
            humansNumber = Integer.parseInt(args[2]);
        }

        Model model = new Model();
        ModelIO.read(model, MAP_DEFAULT);
        View view = new UIView(model);
        ArrayList myPlayers = new ArrayList();

        for (int i = 0; i < humansNumber; i++) {
            Tank tank = new Tank();
            tank.setDirection(Direction.RIGHT);
            tank.setX(0);
            tank.setY(0);
            myPlayers.add(new HumanPlayer(model, tank));
        }

        for (int i = 0; i < botsNumber; i++) {
            myPlayers.add(new Bot(model, model.getPositionedTank()));
        }

        while (!model.isOver()) {
            view.update(null);
            try {
                Thread.sleep(TICK_INTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            String commands = COMMAND_EXIT_CODE;
            Iterator iterator = myPlayers.iterator();
            while (iterator.hasNext()) {
                Player player = (Player) iterator.next();
                commands = view.getStr();
                player.getMove(commands);
            }
            if (commands.contains(COMMAND_EXIT_CODE)) {
                System.exit(0);
            }

            model.tick();
        }

        view.update(null);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}
